# coding=UTF-8
import wsgiref.handlers
from model.article import Article
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import memcache
import datetime
import httplib
import urllib
import hashlib
import feedparser


EMAIL="wwwppp0801@gmail.com"
PASSWD="google1984315"

class SharedTask(webapp.RequestHandler):
    def getSid(self):
        conn = httplib.HTTPSConnection('www.google.com')
        params = urllib.urlencode({'accountType':'HOSTED_OR_GOOGLE','Email':EMAIL,'Passwd':PASSWD})
        headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain"}

        conn.request("POST", "/accounts/ClientLogin", params,headers)
        #conn.request("POST", "/accounts/ClientLogin", 'accountType=HOSTED_OR_GOOGLE&Email=wwwppp0801@gmail.com&Passwd=google1984315')
        response = conn.getresponse()
        if response.status!=httplib.OK:
            print "login error!"
            print response.status, response.reason
        data = response.read()
        #LSID=DQAAAJMAAAAhkwn2P6WLWKfqLKa_zm6sdRF-vHMah9nxa6D83EDaz-4xgOb5UEAGFGvs_szEctSJXxo6EvGGmAxX4FHkv5goJMTdXAfLknz0jVwPUKihXjlDdRrB_uY8JOeyluSkQdR8sdojQsanK3m3mFETl-58B1gk0xC0sSB2dy45B7C3xKEfHT0YuvgCZpYOwKIOZChNuOnKIaetQn-1FpokAc8Y
        sid,lsid=data.split("\n")[:2];
        f = (lambda s : s.split('=')[1])
        sid,lsid=[f(sid),f(lsid)]
        return sid

    def getFeeds(self):
        sid=self.getSid()
        conn = httplib.HTTPConnection('www.google.com')
        #params = urllib.urlencode({'accountType':'HOSTED_OR_GOOGLE','Email':EMAIL,'Passwd':PASSWD})
        #http://www.google.com/reader/atom/user/-/state/com.google/broadcast
        headers = {"Cookie":"SID="+sid}

        conn.request("GET", "/reader/atom/user/-/state/com.google/broadcast",headers=headers)
        response = conn.getresponse()
        if response.status!=httplib.OK:
            print "login error!"
            print response.status, response.reason
        data = response.read()
        #print data
        d=feedparser.parse(data)
        return d
        
    def get(self):
        d=self.getFeeds()
        #print len(d.entries)#.summary_detail.value.encode("utf8")
        #i=0
        for entry in d.entries:
            if hasattr(entry,'summary') or hasattr(entry,'content'):
                if hasattr(entry,'summary'):
                    content=entry.summary
                if hasattr(entry,'content'):
                    content=entry.content[0].value
                m=hashlib.md5()
                m.update(content.encode("utf8"))
                print m.hexdigest()
                if not memcache.add(m.hexdigest(),1):
                    continue
                article=Article()
                article.tags=[]
                article.content = content
                article.title = entry.title
                article.put()

        
    
def main():
  application = webapp.WSGIApplication(
                                       [('/tasks/shared', SharedTask)
                                        ],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == "__main__":
  main()
